<template>
  <div class="publish-page">
    <div class="glass-card">
      <h1 class="page-title">发布新笔记</h1>

      <!-- 标题 -->
      <input
        v-model="noteData.title"
        class="input-field title-input"
        placeholder="添加标题..."
        maxlength="50"
      />

      <!-- 内容 -->
      <textarea
        v-model="noteData.content"
        class="input-field content-input"
        placeholder="分享你的想法、经历或感悟..."
        maxlength="2000"
      />

      <!-- 封面：拖拽 + URL -->
      <section class="section">
        <h3 class="section-title">封面图片</h3>
        <div
          class="drop-zone"
          :class="{ 'active': isDragging }"
          @drop="onDrop"
          @dragover.prevent="isDragging = true"
          @dragleave="isDragging = false"
          @click="openFilePicker"
        >
          <div v-if="!noteData.coverImageUrl" class="drop-hint">
            <PlusIcon class="drop-icon" />
            <span>点击或拖拽图片到这里</span>
          </div>
          <div v-else class="preview-box">
            <img :src="noteData.coverImageUrl" alt="cover" />
            <button class="remove-cover" @click.stop="removeMedia">
              <XIcon size="18" />
            </button>
          </div>
        </div>
        <input
          ref="fileInput"
          type="file"
          accept="image/jpeg,image/png,image/gif"
          hidden
          @change="handleFileUpload"
        />
        <!-- 手动 URL -->
        <div class="url-box">
          <input
            v-model="noteData.coverImageUrl"
            type="url"
            class="url-input"
            placeholder="或粘贴图片地址…"
          />
        </div>
      </section>

      <!-- 标签 -->
      <section class="section">
        <h3 class="section-title">标签（最多 3 个）</h3>
        <div class="tag-list">
          <div
            v-for="tag in allTags"
            :key="tag.id"
            class="tag-chip"
            :class="{ active: noteData.tagIds.includes(tag.id) }"
            @click="toggleTag(tag.id)"
          >
            #{{ tag.name }}
          </div>
        </div>
      </section>

      <!-- 私密 -->
      <section class="section privacy-section">
        <div class="privacy-toggle">
          <input id="private" v-model="noteData.isPrivate" type="checkbox" />
          <label for="private">设为私密笔记</label>
        </div>
      </section>

      <!-- 发布 -->
      <button
        class="publish-btn"
        :disabled="isPublishing || !isFormValid"
        @click="publishNote"
      >
        <span v-if="isPublishing">发布中...</span>
        <span v-else>立即发布</span>
      </button>
    </div>
  </div>
</template>

<script setup>
/* ---------- 基础 ---------- */
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useTagStore } from '@/store/tags'
import { XIcon, PlusIcon } from 'lucide-vue-next'
import { createNote, uploadMedia } from '@/api/notes'

const router = useRouter()
const authStore = useAuthStore()
const tagStore = useTagStore()

/* ---------- 数据 ---------- */
const noteData = ref({
  title: '',
  content: '',
  userId: authStore.user?.id || '',
  isPrivate: false,
  tagIds: [],
  coverImageUrl: ''
})
const isDragging = ref(false)
const isPublishing = ref(false)
const allTags = ref([])
const fileInput = ref(null)

/* ---------- 校验 ---------- */
const isFormValid = computed(() =>
  noteData.value.title.trim().length > 0 &&
  noteData.value.content.trim().length > 0 &&
  noteData.value.userId
)

/* ---------- 生命周期 ---------- */
onMounted(async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login?redirect=publish')
    return
  }
  await tagStore.fetchAllTags()
  allTags.value = tagStore.tags
  noteData.value.userId = authStore.user.id
})

/* ---------- 文件 ---------- */
const openFilePicker = () => fileInput.value?.click()

const handleFileUpload = async (e) => {
  const file = e.target.files?.[0] || e.dataTransfer?.files?.[0]
  if (!file) return
  const max = 5 * 1024 * 1024
  if (file.size > max) return alert('图片大小不能超过5MB')

  const fd = new FormData()
  fd.append('file', file)
  try {
    const res = await uploadMedia(fd)
    noteData.value.coverImageUrl = res.data
  } catch {
    alert('上传失败')
  }
}

const onDrop = (e) => {
  isDragging.value = false
  handleFileUpload(e)
}

const removeMedia = () => {
  noteData.value.coverImageUrl = ''
}

/* ---------- 标签 ---------- */
const toggleTag = (id) => {
  const idx = noteData.value.tagIds.indexOf(id)
  if (idx > -1) noteData.value.tagIds.splice(idx, 1)
  else if (noteData.value.tagIds.length < 3) noteData.value.tagIds.push(id)
}

/* ---------- 发布 ---------- */
const publishNote = async () => {
  isPublishing.value = true
  try {
    await createNote({
      title: noteData.value.title.trim(),
      content: noteData.value.content.trim(),
      userId: noteData.value.userId,
      isPrivate: noteData.value.isPrivate,
      coverImageUrl: noteData.value.coverImageUrl,
      tagIds: noteData.value.tagIds
    })
    alert('发布成功')
    router.push('/')
  } catch (e) {
    console.error(e)
    alert('发布失败')
  } finally {
    isPublishing.value = false
  }
}
</script>

<style scoped>
/* ---------- 玻璃卡 ---------- */
.publish-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.glass-card {
  width: 100%;
  max-width: 680px;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 25px 45px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.page-title {
  text-align: center;
  font-size: 32px;
  font-weight: 700;
  color: #333;
  margin-bottom: 32px;
}

/* ---------- 通用输入 ---------- */
.input-field {
  width: 100%;
  border: none;
  border-bottom: 2px solid rgba(0, 0, 0, 0.08);
  background: transparent;
  padding: 12px 4px;
  font-size: 16px;
  transition: border-color 0.3s;
  outline: none;
}

.input-field:focus {
  border-color:#66D7D2;
}

.title-input {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
}

.content-input {
  min-height: 160px;
  resize: vertical;
  margin-bottom: 32px;
}

/* ---------- 区域标题 ---------- */
.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

/* ---------- 拖拽区 ---------- */
.drop-zone {
  position: relative;
  aspect-ratio: 16 / 9;
  border: 2px dashed rgba(0, 180, 172, 0.4);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.drop-zone.active {
  border-color: #00B4AC;
  background: rgba(0, 180, 172, 0.05);
}

.drop-hint {
  text-align: center;
  color: #00B4AC;
}

.drop-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 8px;
}

.preview-box {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 16px;
  overflow: hidden;
}

.preview-box img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-cover {
  position: absolute;
  top: 12px;
  right: 12px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}

.remove-cover:hover {
  background: rgba(0, 0, 0, 0.7);
}

/* ---------- URL 输入 ---------- */
.url-box {
  margin-top: 12px;
}

.url-input {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.url-input:focus {
  border-color: #00B4AC;
  outline: none;
}

/* ---------- 标签 ---------- */
.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-chip {
  padding: 6px 14px;
  border-radius: 20px;
  background: rgba(0, 180, 172, 0.1);
  color: #00B4AC;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.tag-chip.active {
  background: #00B4AC;
  color: #fff;
}

.tag-chip:hover:not(.active) {
  background: rgba(0, 180, 172, 0.2);
}

/* ---------- 私密切换 ---------- */
.privacy-section {
  margin-top: 24px;
}

.privacy-toggle {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #555;
}

.privacy-toggle input {
  width: 18px;
  height: 18px;
  accent-color: #00B4AC;
}

/* ---------- 发布按钮 ---------- */
.publish-btn {
  width: 100%;
  margin-top: 32px;
  padding: 16px;
  font-size: 18px;
  font-weight: 600;
  color: #fff;
  border: none;
  border-radius: 16px;
  background: #00B4AC;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 15px rgba(0, 180, 172, 0.4);
}

.publish-btn:hover:not(:disabled) {
  box-shadow: 0 6px 20px rgba(0, 180, 172, 0.6);
  transform: translateY(-2px);
}

.publish-btn:disabled {
  background: #ccc;
  box-shadow: none;
  cursor: not-allowed;
}

/* ---------- 响应式 ---------- */
@media (max-width: 600px) {
  .glass-card {
    padding: 24px;
  }
  .page-title {
    font-size: 24px;
  }
}
</style>